package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"user/models"
)

type MainController struct {
	beego.Controller
}
type Res struct {
	Cre  int
	Msg  string
	Data interface{}
}

func (c *MainController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var data []models.UserInit

	shopList := models.RedisDB.Get("shopList")
	if shopList.Val() != "" {
		fmt.Println("有数据")
		//读取缓存数据
		json.Unmarshal([]byte(shopList.Val()), &data)
	} else {
		fmt.Println("无数据")
		models.DB.Debug().Find(&data)
		marshal, _ := json.Marshal(&data)
		//写入缓存
		models.RedisDB.Set("shopList", marshal, 0)
	}
	c.Data["json"] = Res{200, "查询成功", data}
	c.ServeJSON(true)

}

func (c *MainController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	Name := c.GetString("Name")
	Tel := c.GetString("Tel")
	SqTime := c.GetString("SqTime")
	ShopDj := c.GetString("ShopDj")
	shopType := c.GetString("ShopType")
	QtXx := c.GetString("QtXx")

	data := models.UserInit{
		Model:    gorm.Model{},
		Name:     Name,
		Tel:      Tel,
		SqTime:   SqTime,
		ShopDj:   ShopDj,
		ShopType: shopType,
		QtXx:     QtXx,
	}
	models.DB.Create(&data)
	c.Data["json"] = Res{200, "添加成功", data}
	c.ServeJSON(true)

}
